import { sms, setSwitch, login, setRealId } from '../../api/index.js'
import { navigateBackMiniProgram } from '../../utils/util.js'

// pages/loginInfo/loginInfo.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    mobile: '',
    code: '',
    countTime: '获取验证码',
    status: false,
    timer: null,
    realIdentity: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.authorize({
            scope: 'scope.userInfo',
            success() {
              that.getUserInfoWithLogin()
            }
          })
        } else {
          that.getUserInfoWithLogin()
        }
      },
      fail(e) {
        console.log(e, '获取初始化验证身份')
      }
    })
  },

  getUserInfoWithLogin: function () {
    const that = this
    const identity = wx.getStorageSync('identity')

    wx.getUserInfo({
      success: function (info) {
        const { rawData } = info

        wx.setStorageSync('userInfo', rawData)

        wx.login({
          success: function (loginInfo) {
            const { code } = loginInfo
            const result = login({ code, 'raw_data': rawData })

            result.then(res => {
              console.log(res, 888)
              const { real_identity, servant, active} = res
              console.log(identity, 'select identity')
              wx.setStorageSync('token', res.jwt_token)
              wx.setStorageSync('active', active)
              that.setData({
                realIdentity: real_identity
              })

              if (real_identity) {
                that.fetchSwitchIdentity(servant)
              }
            })
              .catch(e => {
                console.log(e, '登录错误')
              })
          },
          fail: function (e) {
            console.log(e, '微信内部登录错误')
          }
        })
      }
    })
  },

  change: function(e) {
    const {detail: {value},currentTarget:{dataset:{info}}} = e

    if (info === 'userName') {
      this.setData({
        name: value
      })
    }else if(info === 'userMobile') {
      this.setData({
        mobile: value
      })
    }else if(info === 'userCode') {
      this.setData({
        code: value
      })
    }
  },

  valid: function() {
    const {name,mobile,code} = this.data

    if(!name) {
      return wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
    }

    if (!mobile) {
      return wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
    }

    if(mobile && mobile.length < 11) {
      return wx.showToast({
        title: '请输入11位手机号码',
        icon: 'none'
      })
    }

    if (!code) {
      return wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      })
    }

    return true
  },

  getSms: function () {
    console.log(555)
    const { mobile } = this.data

    if(!mobile) {
      return wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
    }

    if (mobile) {
      if(mobile.length < 11) {
        return wx.showToast({
          title: '请输入11位手机号码',
          icon: 'none'
        })
      }

      sms({ mobile })
        .then(res => {
          this.count()
        })
        .catch(e => {
          console.log(e, '发送短信')
        })
    }
  },
  count: function () {
    let count = 60
    let { countTime, timer } = this.data
    this.setData({
      status: true,
      countTime: count
    })
    timer = setInterval(() => {
      count--
      console.log(count, 'fff')

      if (count === 0) {
        clearInterval(timer)
        this.setData({
          status: false
        })
      }

      this.setData({
        countTime: count = count === 0 ? '获取验证码' : count
      })

    }, 1000)
  },

  goBack: function() {
    const {timer} = this.data
    const flag = this.valid()

    if (flag) {
      clearInterval(timer)
      this.changeId()
    }
  },

  changeId: function() {
    const {code, name, mobile} = this.data

    setRealId({ code, name, mobile})
    .then(res => {
      console.log(res, '调用切换真实身份')
      this.fetchSwitchIdentity()
    })
    .catch(e => {
      console.log(e,'手机用户信息')
    })

    
  },

  fetchSwitchIdentity: function (servant) {
    const identity = wx.getStorageSync('identity')

    setSwitch({ identity })
      .then(res => {
        console.log(res, '调用切换真实身份')

        if (identity === 'SHOP') {
          if (servant !== undefined && servant === false) {
            wx.navigateTo({
              url: '/pages/selectService/selectService',
            })
          }else {
            navigateBackMiniProgram()
            // wx.navigateTo({
            //   url: '/pages/home/home',
            // })
          }
        } else {
          wx.navigateTo({
            url: '/pages/home/home',
          })
        }
      })
      .catch(e => {
        wx.showToast({
          title: e,
          icon: 'none'
        })

        if (e.statusCode && e.statusCode === 401 && identity !== 'SHOP') {
          wx.navigateTo({
            url: '/pages/region/region',
          })
        }
        console.log(e, '切换身份')
      })
  }

})